const http = require('http');

// 创建测试用户并登录
const userData = JSON.stringify({
  username: 'testuser',
  password: 'testpass'
});

const userOptions = {
  hostname: 'localhost',
  port: 3000,
  path: '/api/login',
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Content-Length': Buffer.byteLength(userData)
  }
};

const userReq = http.request(userOptions, (res) => {
  let data = '';
  
  res.on('data', (chunk) => {
    data += chunk;
  });
  
  res.on('end', () => {
    if (res.statusCode === 200) {
      const userData = JSON.parse(data);
      console.log('User logged in:', userData);
      
      // 创建测试文档
      createTestDocument(userData.user.id);
    } else {
      console.log('Login failed:', data);
    }
  });
});

userReq.on('error', (error) => {
  console.error('User Request Error:', error.message);
});

userReq.write(userData);
userReq.end();

// 创建测试文档
function createTestDocument(userId) {
  const docData = JSON.stringify({
    title: '测试文档 ' + new Date().toLocaleString(),
    content: '这是测试文档的内容',
    ownerId: userId
  });

  const docOptions = {
    hostname: 'localhost',
    port: 3000,
    path: '/api/documents',
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
      'Content-Length': Buffer.byteLength(docData)
    }
  };

  const docReq = http.request(docOptions, (res) => {
    let data = '';
    
    res.on('data', (chunk) => {
      data += chunk;
    });
    
    res.on('end', () => {
      if (res.statusCode === 201) {
        const docData = JSON.parse(data);
        console.log('Document created successfully:', docData);
        console.log('Document ID:', docData.document.id);
        console.log('You can now access the editor at: http://localhost:5173/editor?id=' + docData.document.id);
      } else {
        console.log('Document creation failed:', data);
      }
    });
  });

  docReq.on('error', (error) => {
    console.error('Document Request Error:', error.message);
  });

  docReq.write(docData);
  docReq.end();
}